<template>
  <div>
    <a-space align="center">
      <span>{{ enterpriseName }}</span>
      <span style="margin: 0 6px">{{ nickname }}</span>
      <Badge :dot="hasUnreadMessages" style="margin: 8px 6px">
        <BellOutlined style="margin-top: 12px; font-size: 22px" @click="doShowDrawer" />
      </Badge>
      <a-dropdown placement="bottomRight">
        <template #overlay>
          <a-menu @click="doLoginOut">
            <a-menu-item>
              <template #icon>
                <LogoutOutlined />
              </template>
              <span>退出登录</span>
            </a-menu-item>
          </a-menu>
        </template>
        <a-avatar
          size="max"
          src="https://gw.alipayobjects.com/zos/rmsportal/ubnKSIfAJTxIgXOKlciN.png"
        />
      </a-dropdown>

      <a-drawer
        title="用户消息"
        placement="right"
        :closable="false"
        :visible="showDrawer"
        @close="onClose"
      >
        <div>
          <h3>消息列表</h3>
          <a-list item-layout="horizontal" :data-source="messages">
            <template #loadMore>
              <div
                v-if="canLoadMore"
                :style="{
                  textAlign: 'center',
                  marginTop: '12px',
                  height: '32px',
                  lineHeight: '32px',
                }"
              >
                <a-button @click="onLoadMore">加载更多</a-button>
              </div>
            </template>
            <template #renderItem="{ item }">
              <a-list-item>
                <template #actions>
                  <a-button type="text" @click="markAsRead(item.id)" v-if="item.status === '0'">
                    <CheckOutlined />
                  </a-button>
                </template>
                <a-list-item-meta
                  :class="[item.status === '1' ? 'read-message' : 'unread-message']"
                  :description="item.content"
                >
                  <template #title>
                    {{ item.msgType === '1' ? '系统消息' : '其他消息' }}
                  </template>
                  <template #avatar>
                    <a-avatar
                      src="https://gw.alipayobjects.com/zos/rmsportal/ubnKSIfAJTxIgXOKlciN.png"
                    />
                  </template>
                </a-list-item-meta>
              </a-list-item>
            </template>
          </a-list>
        </div>
      </a-drawer>
    </a-space>
  </div>
</template>

<script setup lang="ts">
import { BellOutlined, CheckOutlined, LogoutOutlined } from '@ant-design/icons-vue';
import { useRouter } from 'vue-router';
import { Badge, notification } from 'ant-design-vue';
import { count, page, update } from '@/services';
import { ref, watch } from 'vue';

const nickname = localStorage.getItem('username');
const enterpriseName = localStorage.getItem('enterprise_name');

const router = useRouter();

const doLoginOut = async () => {
  localStorage.removeItem('access_token');
  localStorage.removeItem('username');
  await router.push({ path: '/login' });
  notification.success({
    message: '欢迎',
    description: `您已退出登录`,
  });
};

window.addEventListener('logout', async () => {
  await router.push({ path: '/login' });
});

const hasUnreadMessages = ref(false);

const fetchUserMsgCount = async () => {
  const response = await count('/api/elog/userMsg');
  hasUnreadMessages.value = response.data > 0;
};

const markAsRead = async id => {
  const readStatus = '1';
  const res = await update('/api/elog/userMsg', { id, status: readStatus });
  if (res.success && res.data) {
    messages.value = messages.value.map(msg =>
      msg.id === id ? { ...msg, status: readStatus } : msg,
    );
  }
};
onMounted(() => {
  fetchUserMsgCount();
});

const doShowDrawer = async () => {
  current.value = 1;
  showDrawer.value = true;
};
const onClose = () => {
  showDrawer.value = false;
};

const showDrawer = ref(false);

const messages = ref([]);

const canLoadMore = ref(true);
const current = ref(0);

const doSearch = async () => {
  const params = { current: current.value, pageSize: 10, data: {} };

  const res = await page(`/api/auth/tUserMsg`, params);
  const { success, page: pageData } = res;
  if (success) {
    const { list: listData } = pageData;
    if (!listData) {
      canLoadMore.value = false;
      return;
    }
    if (current.value == 1) {
      messages.value = [...listData];
    } else {
      messages.value = [...messages.value, ...listData];
    }
  }
};

watch(current, doSearch);

const onLoadMore = async () => {
  current.value += 1;
};
</script>

<style scoped>
.unread-message {
  font-weight: 700;
}

.read-message {
  font-weight: 400;
}

.page_dropdown {
  padding-right: 60px;
}
</style>
